package com.zjdiepu.www.biz.cw;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.AddedStatus1;
import com.zjdiepu.www.base.enums.status.RemitStatus;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SysParamsType;
import com.zjdiepu.www.biz.helper.ServiceHelper;
import com.zjdiepu.www.dao.cw.CwRefundCarMapper;
import com.zjdiepu.www.dao.cw.CwRemitCarMapper;
import com.zjdiepu.www.dao.other.OtherWantWarningMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.cw.ICwRemitCarService;
import com.zjdiepu.www.ibiz.system.IBaseSysParamsService;
import com.zjdiepu.www.ibiz.system.IOtherHolidaysService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessExtrasService;
import com.zjdiepu.www.ibiz.zpp.SystemService;
import com.zjdiepu.www.model.cw.dto.CwRefundCar;
import com.zjdiepu.www.model.cw.dto.CwRemitCar;
import com.zjdiepu.www.model.cw.ext.CwRefundCarExt;
import com.zjdiepu.www.model.cw.ext.CwRemitCarExt;
import com.zjdiepu.www.model.other.dto.OtherMessageApp;
import com.zjdiepu.www.model.other.dto.OtherWantWarning;
import com.zjdiepu.www.model.yw.dto.YwBusiness;

/**
 * 垫提车款Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月11日 20时36分<br/>
 * @since 1.0<br/>
 */
@Service
public class CwRemitCarServiceImpl extends BaseService implements ICwRemitCarService {
	public static final Logger logger = LoggerFactory.getLogger(CwRemitCarServiceImpl.class);
	@Autowired
	private SystemService systemService;
	@Autowired
	private CwRemitCarMapper cwRemitCarMapper;
	@Autowired
	private CwRefundCarMapper cwRefundCarMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private ServiceHelper serviceHelper;
	@Resource
	private OtherWantWarningMapper otherWantWarningMapper;
	@Resource
	private IBaseSysParamsService baseSysParamsService;
	@Resource
	private IOtherHolidaysService otherHolidaysService;
	@Resource
	private IYwBusinessExtrasService ywBusinessExtrasService;
	
	@Override
	public CwRemitCar getRemitNotRefund(String busiId) {
		if(StringUtils.isBlank(busiId)) {
			return null;
		}
		CwRemitCarExt cwRemitCarExt = new CwRemitCarExt();
		cwRemitCarExt.setBaseWhere();
		cwRemitCarExt.withOutPage();
		cwRemitCarExt.setBusiId(busiId);
		List<CwRemitCar> cwRemitCars = cwRemitCarMapper.selectByExt(cwRemitCarExt);
		if(CollectionUtils.isEmpty(cwRemitCars)) {
			return null;
		}
		outter:for(CwRemitCar cwRemitCar : cwRemitCars) {
			CwRefundCarExt cwRefundCarExt = new CwRefundCarExt();
			cwRefundCarExt.setBaseWhere();
			cwRefundCarExt.withOutPage();
			cwRefundCarExt.setBusiId(busiId);
			List<CwRefundCar> cwRefundCars = cwRefundCarMapper.selectByExt(cwRefundCarExt);
			for(CwRefundCar cwRefundCar : cwRefundCars) {
				if(cwRemitCar.getId().equals(cwRefundCar.getRemitId())) { //已经退款
					continue outter;
				}
			}
			return cwRemitCar;
		}
		return null;
	}
	
	@Override
	public ApiResponse saveRemitCar(CwRemitCar cwRemitCar,boolean commit, 
			AbstractSysUser currentUser) {
		String id = cwRemitCar.getId();
		if(StringUtils.isBlank(cwRemitCar.getFundApplyId())){
			return ApiResponse.fail(999,"请刷新页面，并确认已经申请垫资");
		}
		if(ywBusinessExtrasService.checkLoanEditLock(cwRemitCar.getBusiId())) {
			return ApiResponse.fail(999,"该订单正在申请修改贷款信息，不允许操作");
		}
		cwRemitCar.setStatusRemit(commit ? RemitStatus.YI_TI_JIAO.getCode() : RemitStatus.WEI_TI_JIAO.getCode());
		if(StringUtils.isBlank(id)) {
			cwRemitCar.initInsertData(currentUser.getId(), currentUser.getName());
			cwRemitCarMapper.insert(cwRemitCar);
		} else {
			cwRemitCar.initUpdateData(currentUser.getId(), currentUser.getName());
			cwRemitCarMapper.updateByPrimaryKeySelective(cwRemitCar);
		}
		
		if(commit) {
			if(!cwRemitCar.isCompleted()) {
				return ApiResponse.fail(999,"垫提车款资料不完整");
			}
			YwBusiness ywBusiness = new YwBusiness();
			ywBusiness.setId(cwRemitCar.getBusiId());
//			ywBusiness.setBusiStatus(BusiStatus.YI_DA_KUAN.getCode());
			ywBusiness.setAddedStatus1(AddedStatus1.YI_DA_KUAN.getCode());
			ywBusiness.setFundChannel(cwRemitCar.getFundChannel());
			ywBusiness.setLoanTime(cwRemitCar.getTimeRemit());
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
			ywBusiness = ywBusinessMapper.selectByPrimaryKey(cwRemitCar.getBusiId());	
			String busiId = cwRemitCar.getBusiId();
			String dataId = cwRemitCar.getId();
			
			YwBusiness dbYwBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
			String customerName = dbYwBusiness.getCustomerName();
			String salesmanId = dbYwBusiness.getSalesmanId();
			
			//财务打款通知
			/*String nameAuditor = cwRemitCar.getNameAuditor();
			Date timeAudit = cwRemitCar.getTimeAudit();
			String bankLoanDisplay = dbYwBusiness.getBankLoanDisplay();
			OtherMessageApp otherMessageApp = new OtherMessageApp();
			otherMessageApp.setModeId(ModeIDType.DKDJ.getCode());
			otherMessageApp.setBusiId(busiId);
			otherMessageApp.setDataid(dataId);
			otherMessageApp.setTypeMsg("02");
			otherMessageApp.setTypeMsgEvent("20");
			otherMessageApp.setNotificationBar(customerName + "的订单，财务已打款");
			otherMessageApp.setTitle(customerName + "的订单，财务已打款");
			otherMessageApp.setContent("通知：" + customerName + "的订单，财务已打款<br/>打款银行：" + bankLoanDisplay+ "<br/>财务审核人："
			+ nameAuditor + "<br/>财务审核时间：" + DateUtil.dateTo12String(timeAudit));
			otherMessageApp.setTimeCreate(new Date());
			
			String shortMessage = "客户" + customerName +"的订单，财务已打款";
			serviceHelper.saveMsg(otherMessageApp,customerId, customerName, shortMessage, currentUser, logger);*/
			
			//删除财务打款预警信息
			OtherWantWarning dzOtherWantWarning = new OtherWantWarning();
			dzOtherWantWarning.setBusiId(busiId);
			dzOtherWantWarning.setModeId(ModeIDType.CWDK.getCode());
			otherWantWarningMapper.deletedReal(dzOtherWantWarning);
			
			//提车+上牌提示
//			OtherMessageApp otherMessageApp_ = new OtherMessageApp();
//			otherMessageApp_.setModeId(ModeIDType.TC.getCode());
//			otherMessageApp_.setBusiId(busiId);
//			otherMessageApp_.setDataid(dataId);
//			otherMessageApp_.setTypeMsg("01");
//			otherMessageApp_.setTypeMsgEvent("21");
//			otherMessageApp_.setNotificationBar(customerName + "的订单，请及早提车上牌");
//			otherMessageApp_.setTitle(customerName + "的订单，请及早提车上牌");
//			otherMessageApp_.setContent("提示：" + customerName + "的订单，财务已打款，请及早提车上牌");
//			Date now = new Date();
//			otherMessageApp_.setTimeCreate(now);
//			otherMessageApp_.setTimeSend(now);
//			otherMessageApp_.setStatusMsg(MessageStatus.WEI_TUI_SONG.getCode());
//			
//			String shortMessage_ = "客户" + customerName +"的订单，财务已打款，请及早提车上牌";
//			serviceHelper.saveMsg(otherMessageApp_, salesmanId, customerName, shortMessage_, currentUser, logger);
			
			systemService.diepuNewsHandle(currentUser, ModeIDType.TC.getCode(), "21", busiId, null);
			
			//绿色通道
			if("50".equals(ywBusiness.getChannelType())) {
				systemService.diepuNewsHandle(currentUser, ModeIDType.ZSYS.getCode(), "33", busiId, null, cwRemitCar.getReceiverIds());
			}
			
			//提车预警
			OtherWantWarning otherWantWarning = new OtherWantWarning();
			otherWantWarning.initInsertData(currentUser.getId(), currentUser.getName());
			otherWantWarning.setModeId(ModeIDType.TC.getCode());
			otherWantWarning.setBusiId(busiId);
			otherWantWarning.setDataid(dataId);
			otherWantWarning.setTypeMsg("03");
			otherWantWarning.setTypeMsgEvent("22");
			//预警时间
			Integer paramIntValue = (Integer)SysParamsType.TI_CHE_CHAO_QI_YU_JING.getDefaultValue();
			String paramValue = baseSysParamsService.getValueByCode(SysParamsType.TI_CHE_CHAO_QI_YU_JING.getCode());
			if(StringUtils.isNotBlank(paramValue)) {
				paramIntValue = Integer.valueOf(paramValue);
			}
			Date nextWorkDate = otherHolidaysService.getNextWorkDate(new Date(), "1", paramIntValue);
			otherWantWarning.setTimeWarning(nextWorkDate);
			otherWantWarning.setStatusMsg(1);
			
			OtherMessageApp tcAlertMsg = new OtherMessageApp();
			tcAlertMsg.setModeId(ModeIDType.TC.getCode());
			tcAlertMsg.setBusiId(busiId);
			tcAlertMsg.setDataid(dataId);
			tcAlertMsg.setTypeMsg("03");
			tcAlertMsg.setTypeMsgEvent("22");
			tcAlertMsg.setNotificationBar("客户" + customerName + "的订单 请尽快提车");
			tcAlertMsg.setTitle("客户" + customerName + "的订单 请尽快提车");
			tcAlertMsg.setContent("预警：客户" + customerName + "的订单 请尽快提车");
			tcAlertMsg.setTimeCreate(new Date());
			String tcShortMessage = "预警：客户" + customerName + "的订单 请尽快提车";
			
			serviceHelper.saveAlert(otherWantWarning, tcAlertMsg, salesmanId, customerName, tcShortMessage, currentUser);
		}
		
		return ApiResponse.success(cwRemitCar.getId());
	}
	
	@Override
	public String queryHistoryByBusiId(String busiId) {
		return cwRemitCarMapper.queryHistoryByBusiId(busiId,RemitStatus.YI_TI_JIAO.getCode());
	}
	
	@Override
	public void saveUpdateAndDelete(CwRemitCar cwRemitCar, OperateType operType) {
		switch (operType) {
		case add:
			cwRemitCar.initInsertData(cwRemitCar.getModifier(), cwRemitCar.getModifierName());
			cwRemitCarMapper.insert(cwRemitCar);
			break;
		case edit:
			cwRemitCar.initUpdateData(cwRemitCar.getModifier(), cwRemitCar.getModifierName());
			// 影响的记录数
			int updateCount = cwRemitCarMapper.updateByPrimaryKeySelective(cwRemitCar);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			cwRemitCar.initDeleteData(cwRemitCar.getModifier(), cwRemitCar.getModifierName());
			// 影响的记录数
			int deleteCount = cwRemitCarMapper.updateByPrimaryKeySelective(cwRemitCar);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<CwRemitCar> selectByExt(CwRemitCarExt cwRemitCarExt) {
		return cwRemitCarMapper.selectByExt(cwRemitCarExt);
	}
	
	@Override
	public int countByExt(CwRemitCarExt cwRemitCarExt){
		return cwRemitCarMapper.countByExt(cwRemitCarExt);
	}
	
	@Override
	public CwRemitCar selectById(String id) {
		return cwRemitCarMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			cwRemitCarMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(CwRemitCar cwRemitCar) {
		return cwRemitCarMapper.countRefined(cwRemitCar);
	}

	@Override
	public CwRemitCar selectRefined(CwRemitCar cwRemitCar) {
		return cwRemitCarMapper.selectRefined(cwRemitCar);
	}
	
	@Override
	public int deletedRefined(CwRemitCar cwRemitCar) {
		return cwRemitCarMapper.deletedRefined(cwRemitCar);
	}

	@Override
	public boolean repeat(CwRemitCar cwRemitCar) {
		int count = countRefined(cwRemitCar);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(cwRemitCar.getId())) {
			return true;
		}
		CwRemitCar dbItem = selectRefined(cwRemitCar);
		if(null == dbItem) {
			return false;
		}
		return !cwRemitCar.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return cwRemitCarMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<CwRemitCar> cwRemitCars) {
		return cwRemitCarMapper.insertBatch(cwRemitCars);
	}

	@Override
	public void updateArriveTime(Date timeArrive, List<String> ids) {
		cwRemitCarMapper.updateArriveTime(timeArrive,ids);
		
	}
}
